<template>
	<view class="aiWriting_box">
		<view class="content">
			<view class="textarea">
				<u-textarea height="722rpx" maxlength="5000" v-model="writing" border="false" placeholder="点击输入文案或长按粘贴文案">
				</u-textarea>
			</view>
			<view class="tools">
				<view class="tools_left">
					<view class="left" @click="delWriting">
						<u-icon name="trash" size="18" color="#999999"></u-icon>
						<text class="text">清除文本</text>
					</view>
					<view class="right" @click="goTextDetection(writing,0)">
						<text class="text">敏感词检测</text>
					</view>
				</view>
				<view class="tools_right">
					<text class="text">字数 {{writing.length}}</text>
				</view>
			</view>
		</view>
		<view class="button">
			<view class="button_left">
				<u-button text="伪原创" color="#5490FF" size="large" @click="goTextDetection(writing,1)"></u-button>
			</view>
			<view class="button_right">
				<u-button text="AI伪原创" color="#1EB930" size="large" @click="goTextDetection(writing,2)"></u-button>
				<view class="right_other">
					<text>每次改写都不同</text>
				</view>
			</view>
		</view>
		<view class="originality" v-if="creativeResults.length!=0">
			<ul>
				<li>
					<view class="left" style="background-color: #1EB930;">
						今日次数
					</view>
					<view class="right">
						{{isVip? '不限': frequency}}
					</view>
				</li>
				<li>
					<view class="left" style="background-color: #5490FF;margin-left: 33rpx;">
						AI级别
					</view>
					<view class="right">
						{{aiLevel}}
					</view>
				</li>
				<li>
					<view class="left" style="background-color: #5490FF;margin-left: 33rpx;">
						原创度
					</view>
					<view class="right">
						{{originality}}
					</view>
				</li>
			</ul>
		</view>
		<view class="creative_results" v-if="creativeResults.length!=0">
			<view class="title">
				创作结果
			</view>
			<view class="results_textarea" style="padding: 0 20rpx 20rpx 20rpx;">
				<!-- <u-textarea autoHeight maxlength="-1" v-model="creativeResults" border="false" placeholder="创作结果">
				</u-textarea> -->
				<view user-select='true'
					style="width:100%;color: #606266;font-size: 15px;display:inline-block;white-space: pre-wrap; word-wrap: break-word;height: auto;">
					{{creativeResults}}
				</view>
			</view>
			<view class="creative_results_btn" @click="copyResults">
				<u-button text="复制结果" color="#5490FF" size="large"></u-button>
			</view>
		</view>
		<view class="creative_results" v-if="creativeResults.length!=0">
			<view class="title">
				摘要结果
			</view>
			<view class="results_textarea" style="padding: 0 20rpx 20rpx 20rpx;">
				<!-- <u-textarea autoHeight maxlength="-1" v-model="abstractResults" border="false" placeholder="摘要结果">
				</u-textarea> -->
				<view user-select='true' style="color: #606266;font-size: 15px;">
					{{abstractResults}}
				</view>
			</view>
			<view class="creative_results_btn" @click="copyAbstractResults">
				<u-button text="复制摘要" color="#5490FF" size="large"></u-button>
			</view>
		</view>
		<view class="creative_results" v-if="creativeResults.length!=0">
			<view class="title">
				关键词提取
			</view>
			<view class="results_keyWords">
				<ul>
					<li v-for="(item,index) in results" :key="index">
						<view class="">
							{{item.word}}
						</view>
						<view class="">
							{{(item.score*100).toFixed(2)}}%
						</view>
					</li>
				</ul>
			</view>
			<view class="creative_results_btn" @click="copyKeyWordsResults">
				<u-button text="复制关键词" color="#5490FF" size="large"></u-button>
			</view>
		</view>
		<view class="result_comparison" v-if="creativeResults.length!=0">
			<view class="title">
				结果比较
			</view>
			<view class="results_textarea">
				<text user-select='true' v-for="(item,index) in  compareResults" :key='index'
					:style="{color:!!item.color?item.color:'#606266',fontSize:!!item.fontSize? item.fontSize:'15px'}">{{item.value}}</text>
			</view>
		</view>
		<view style="width: 100%; height: 31rpx;background-color: #f4f4f4;"></view>
		<!-- 非会员看广告提示 -->
		<u-modal :show="vipShow" :title="'温馨提示'" :content="content" cancelText="取消" confirmText="去开通"
			showCancelButton="true" @cancel="cancel" @confirm="govip" :closeOnClickOverlay="true"
			@close="vipShow = false"></u-modal>
	</view>
</template>

<script>
	import {
		isLogin,
		vipType
	} from '@/business/login.js';
	import {
		wycUrl,
		wycUrlApi,
		apiMixUrlApi
	} from '@/api/assemb.js'
	import {
		wxTextDetection
	} from "../../utils/textCheck.js";
	import {
		_log
	} from 'umtrack-tt';
	var diff = require('diff');
	let app = getApp();
	export default {
		data() {
			return {
				isVip: false,
				content: '您还不是会员,此功能需开通会员才可使用。',
				writing: '',
				creativeResults: '',
				compareResults: [],
				abstractResults: '',
				results: [],
				vipShow: false,
				frequency: uni.getStorageSync('frequency'),
				aiLevel: 1,
				originality: 0,
				accessToken: ''
			};
		},
		onShow() {
			this.isVip = uni.getStorageSync('vipType').vipStatus == 1 ? true : false;
			// this.isVip = true;
		},
		onLoad() {
			this.frequency = uni.getStorageSync('frequency') || 3
			this.accessToken = getApp().globalData.accessToken
			if (this.frequency != 1 && this.frequency != 2) {
				uni.setStorageSync('frequency', 3)
			}
		},
		methods: {
			copyKeyWordsResults() {
				var txtRes = ''
				this.results.forEach((item) => {
					txtRes = txtRes + item.word + ','
				})
				txtRes = txtRes.slice(0, txtRes.length - 1)
				uni.setClipboardData({
					data: txtRes,
					showToast: true
				});
			},
			copyAbstractResults() {
				uni.setClipboardData({
					data: this.abstractResults,
					showToast: true
				});
			},
			/**
			 * 跳转充值页面
			 */
			govip() {
				this.vipShow = false;
				if (uni.getStorageSync('OS') !== 'ios') {
					uni.navigateTo({
						url: '/pages/paymentCenter/paymentCenter'
					});
				} else {
					uni.showModal({
						title: '提示',
						content: '由于相关规范，IOS功能暂不可用',
						showCancel: false,
						success: function(res) {
							if (res.confirm) {
								console.log('用户点击确定');
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					});
				}
			},
			cancel() {
				this.vipShow = false;
				// 用户触发广告后，显示激励视频广告
				// if (videoAd) {
				// 	videoAd.show().catch(() => {
				// 		// 失败重试
				// 		videoAd
				// 			.load()
				// 			.then(() => videoAd.show())
				// 			.catch(err => {
				// 				console.log('激励视频 广告显示失败');
				// 			});
				// 	});
				// }
			},
			async original(param) {
				uni.showLoading({
					title: '加载中...',
					mask: true
				});
				await wycUrl(param, 1007, 'pseudoAzure').then((res) => {
					if (!this.isVip) {
	  				let param = {
	  					consumecoins: 1,
	  					descinfo: '一键创作消耗',
	  					consumetype: 1,
	  				}
	  				apiMixUrlApi(param, '1043', "ConsumeCoins").then(result => {
	  					console.log(result, '1043返回值');
	  					uni.setStorageSync('frequencyrs', result.coins)
	  				});
	  			}
					this.creativeResult += res.data.data.results[0]
					uni.hideLoading();
				})
			},
			// AI伪原创
			async highOriginal() {
				this.creativeResult = ''
				if (this.writing.trim() == '') {
					uni.showToast({
						title: '请输入文案',
						duration: 2000,
						icon: 'none'
					});
				} else if (uni.getStorageSync('frequency') > 1 || this.isVip) {
					if (this.writing.trim().length < 400 || this.isVip) {
						let str = this.writing,
							arr = [] //用于保存每次截取后的字符串
						biali(str, 0);
						console.log(arr);

						function biali(x, z) {
							var m = x.substr(z, 5000);
							var f = ['。', ',', '.', '?', ';', '!', '，', '？', '！', '；'];
							var y = 5000;
							var ynum = [];
							for (var j = 0; j < f.length; j++) {
								if (m.lastIndexOf(f[j]) > 0) {
									ynum.push(m.lastIndexOf(f[j]));
								}
							}
							if (ynum.length > 0) {
								y = (Math.max.apply(null, ynum) + 1);
							}
							arr.push(x.substr(z, y));
							z += y;
							if (m.length >= 5000) {
								return biali(x, z);
							}
						}
						for (var i = 0; i < arr.length; i++) {
							console.log("第" + i + "个分割后的字符是：" + arr[i]);
							let param = {
								"content": `请将下面文字进行伪原创:'${arr[i]}'`
							}
							console.log(param);
							await this.original(param)
						}
						this.creativeResults = this.creativeResult.replace(/[\r\n]/g, '')
						uni.showLoading({
							title: '加载中...',
							mask: true
						});
						let diffResult = diff.diffChars(this.writing, this.creativeResults)
						if (diffResult.length) {
							diffResult.map(item => {
								if (!!item.added) {
									item.color = '#73A1FF'
								}
								if (!!item.removed) {
									item.color = '#999999'
									item.fontSize = '18rpx'
								}
							})
						}
						this.compareResults = diffResult
						this.originality = this.similar(this.writing, this.creativeResults, 2)
						this.aiLevel = 3
						this.generateAbstract()
						this.getKeyWords()
						uni.hideLoading();

					} else {
						this.content = '字数超限了,开通会员不限字数。'
						this.vipShow = true
					}

				} else {
					this.content = '今日免费次数已用完,需开通会员才可使用。'
					this.vipShow = true
				}
			},
			// 免费伪原创
			freeOriginal() {
				if (this.writing.trim() == '') {
					uni.showToast({
						title: '请输入文案',
						duration: 2000,
						icon: 'none'
					});
				} else if (uni.getStorageSync('frequency') > 1 || this.isVip) {
					if (this.writing.trim().length < 400 || this.isVip) {
						uni.showLoading({
							title: '加载中...',
							mask: true
						});
						let data = {
							v: 3,
							token: 'kKxkAbJBNQ',
							type: 'txt',
							content: this.writing
						}
						wycUrlApi(data).then((res) => {
							if (uni.getStorageSync('frequency') > 1) {
								uni.setStorageSync('frequency', uni.getStorageSync('frequency') -
									1)
								this.frequency = uni.getStorageSync('frequency') - 1
							}
							this.creativeResults = res.data.data.content
							uni.showLoading({
								title: '加载中...',
								mask: true
							});
							let diffResult = diff.diffChars(this.writing, this.creativeResults)
							if (diffResult.length) {
								diffResult.map(item => {
									if (!!item.added) {
										item.color = '#73A1FF'
									}
									if (!!item.removed) {
										item.color = '#999999'
										item.fontSize = '18rpx'
									}
								})
							}
							this.compareResults = diffResult
							this.originality = this.similar(this.writing, this.creativeResults, 2)
							this.aiLevel = 3
							this.generateAbstract()
							this.getKeyWords()
							uni.hideLoading();
						})
					} else {
						this.content = '字数超限了,开通会员不限字数。'
						this.vipShow = true
					}

				} else {
					this.content = '今日免费次数已用完,需开通会员才可使用。'
					this.vipShow = true
				}
			},
			getKeyWords() {
				wx.request({
					url: `https://aip.baidubce.com/rpc/2.0/nlp/v1/txt_keywords_extraction?access_token=${this.accessToken}&charset=UTF-8`,
					method: "POST",
					data: {
						text: [this.writing],
						num: 20
					},
					success: (res) => {
						console.log(res);
						this.results = res.data.results
					}
				})
			},
			generateAbstract() {
				wx.request({
					url: `https://aip.baidubce.com/rpc/2.0/nlp/v1/news_summary?access_token=${this.accessToken}&charset=UTF-8`,
					method: "POST",
					data: {
						content: this.writing.slice(0, 3000),
						max_summary_len: 200
					},
					success: (res) => {
						console.log(res);
						this.abstractResults = res.data.summary
					}
				})
			},
			similar(s, t, f) {
				if (!s || !t) {
					return 0
				}
				if (s === t) {
					return 100;
				}
				var l = s.length > t.length ? s.length : t.length
				var n = s.length
				var m = t.length
				var d = []
				f = f || 2
				var min = function(a, b, c) {
					return a < b ? (a < c ? a : c) : (b < c ? b : c)
				}
				var i, j, si, tj, cost
				if (n === 0) return m
				if (m === 0) return n
				for (i = 0; i <= n; i++) {
					d[i] = []
					d[i][0] = i
				}
				for (j = 0; j <= m; j++) {
					d[0][j] = j
				}
				for (i = 1; i <= n; i++) {
					si = s.charAt(i - 1)
					for (j = 1; j <= m; j++) {
						tj = t.charAt(j - 1)
						if (si === tj) {
							cost = 0
						} else {
							cost = 1
						}
						d[i][j] = min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost)
					}
				}
				let res = (1 - (1 - d[n][m] / l)) * 100
				return res.toFixed(f)
			},
			copyResults() {
				uni.setClipboardData({
					data: this.creativeResults,
					showToast: true
				});
			},
			delWriting() {
				this.writing = ''
			},
			goTextDetection(writing, data) {
				if (writing.trim() == '') {
					uni.showToast({
						title: '请输入文案',
						duration: 2000,
						icon: 'none'
					});
				} else {
					uni.showLoading({
						title: '检测中...',
						mask: true
					});
					let prams = {
						text: writing.substring(0, 3000)
					}
					apiMixUrlApi(prams, 1089, 'DYTextCheck').then((res) => {
						console.log(res);
						uni.hideLoading()
						if (!res.hit) {
							if (data == 0) {
								tt.showModal({
									title: "提示",
									content: "未检测到敏感关键词",
									showCancel: false,
									success(res) {},
								});
							} else if (data == 1) {
								this.freeOriginal()
							} else {
								this.highOriginal()
							}
						} else {
							tt.showModal({
								title: "提示",
								content: "检测到敏感关键词，请修改后重试！",
								showCancel: false,
								success(res) {},
							});
						}
					})
				}

			}
		}
	}
</script>

<style lang="scss">
	/deep/.u-textarea--disabled {
		background-color: #fff !important;
	}

	/deep/.u-textarea {
		padding-top: 0 !important;
		padding-bottom: 0 !important;
	}

	/deep/.u-button {
		border-radius: 12rpx !important;
	}

	/deep/.u-icon__icon {
		margin-right: 8rpx !important;
	}

	/deep/.u-checkbox__icon-wrap {
		width: 26rpx !important;
		height: 26rpx !important;
		margin-left: 57rpx;
	}


	.title {
		line-height: 111rpx;
		margin-left: 268rpx;
		font-size: 34rpx;
		font-family: PingFang SC;
		color: #5490FF;
	}

	.result_comparison {
		margin-top: 31rpx;
		margin-bottom: 20rpx;
		width: 696rpx;
		background: #FFFFFF;
		border-radius: 18rpx;

		.results_textarea {
			padding: 0 20rpx 20rpx 20rpx;
		}
	}


	.creative_results {
		padding-bottom: 30rpx;
		margin-top: 20rpx;
		width: 696rpx;
		background: #FFFFFF;
		border-radius: 18rpx;
		box-sizing: border-box;

		.creative_results_btn {
			margin: auto;
			margin-top: 30rpx;
			width: 333rpx;
		}

		.results_keyWords {
			li {
				display: flex;
				justify-content: space-around;
				color: #5490FF;
				font-size: 32rpx;
			}
		}

	}

	.originality {
		margin-top: 64rpx;

		ul {
			display: flex;

			li {
				display: flex;
				width: 193rpx;
				height: 43rpx;
				font-size: 18rpx;

				.left {
					width: 102rpx;
					height: 43rpx;
					color: #FFFFFF;
					text-align: center;
					line-height: 43rpx;
					border-radius: 6rpx 0rpx 0rpx 6rpx;
				}

				.right {
					width: 92rpx;
					height: 43rpx;
					color: #333333;
					text-align: center;
					line-height: 43rpx;
					background-color: #fff;
					border-radius: 0rpx 6rpx 6rpx 0rpx;
				}
			}
		}
	}

	.button {
		margin-top: 62rpx;
		width: 100%;
		display: flex;
		justify-content: space-between;

		.button_left {
			width: 47%;
		}

		.button_right {
			position: relative;
			width: 47%;

			.right_other {
				display: flex;
				align-items: center;
				position: absolute;
				top: -21rpx;
				right: 0;
				width: 154rpx;
				height: 42rpx;
				background: #FF6600;
				border-radius: 21rpx 0rpx 0rpx 21rpx;

				text {
					line-height: 42rpx;
					margin-left: 18rpx;
					font-size: 18rpx;
					font-family: PingFang SC;
					color: #FFFFFF;
				}
			}
		}
	}

	.textarea {
		height: 722rpx;
	}

	.text {
		font-size: 19rpx;
		font-family: PingFang SC;
		color: #999999;
	}

	.aiWriting_box {
		padding: 0 27rpx;

		.content {
			width: 696rpx;
			height: 822rpx;
			border-radius: 18rpx;
			background-color: #fff;
		}

		.tools {
			height: 100rpx;
			padding: 0 27rpx;
			display: flex;
			justify-content: space-between;

			.tools_left {
				display: flex;
				justify-content: space-between;

				.left {
					display: flex;
					justify-content: space-between;
					align-items: center;
				}

				.right {
					margin-left: 40rpx;
					display: flex;
					justify-content: space-between;
					align-items: center;
				}
			}

			.tools_right {
				display: flex;
				align-items: center;
			}
		}
	}
</style>
<style>
	page {
		background-color: #f4f4f4;
	}
</style>